package utils

import (
	"io"
	"os"
	"path/filepath"
)

func CopyFile(src, dst string) (err error) {
	in, err := os.Open(src)
	if err != nil {
		return err
	}
	defer in.Close()

	err = CreateBaseDir(dst)
	if err != nil {
		return err
	}
	out, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer func() {
		out.Close()
	}()
	if _, err = io.Copy(out, in); err != nil {
		return err
	}
	err = out.Sync()
	return err
}

// CreateBaseDir 根据文件路径创建目录
func CreateBaseDir(fPath string) error {
	baseDir := filepath.Dir(fPath)
	info, err := os.Stat(baseDir)
	if err == nil && info.IsDir() {
		return nil
	}
	return os.MkdirAll(baseDir, 0755)
}

func SaveBytesToDisk(fileName string, bucket []byte) (string, error) {
	outFile, err := os.Create(fileName)
	if err != nil {
		return "", err
	}

	_, err = io.Writer.Write(outFile, bucket)
	outFile.Close()

	return fileName, err
}

func GetCurrentAbs() (string, error) {
	//返回绝对路径 filepath.Dir(os.Args[0])去除最后一个元素的路径
	return filepath.Abs(os.Args[0])
}
